package com.tomato.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tomato.order.VO.ResultVO;
import com.tomato.order.config.ProjectUrlConfig;
import com.tomato.order.entity.*;
import com.tomato.order.mapper.*;
import com.tomato.order.util.R;
import org.apache.catalina.Store;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class ServerController {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderMasterMapper orderMasterMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private ProjectUrlConfig projectUrlConfig;
    @Resource
    private TableMapper tableMapper;
    @Resource
    private SellerMapper sellerMapper;
    @Resource
    private UserMapper userMapper;

    @RequestMapping("/category/list")
    public List categoryList() {
        return categoryMapper.selectList(null);
    }

    @RequestMapping("/categories")
    public IPage<Category> categories(@RequestParam(value = "page", defaultValue = "1") String page,
                                      @RequestParam(value = "size", defaultValue = "10") String size,
                                      @RequestParam(value = "searchName", defaultValue = "") String searchName) {
        Page<Category> categoryPage = new Page<>(Integer.valueOf(page), Integer.valueOf(size));
        IPage<Category> categoryIPage = categoryMapper.selectPage(categoryPage, new QueryWrapper<Category>().
                like("name", searchName).
                orderByAsc("type"));
        return categoryIPage;
    }

    @RequestMapping("/category/save")
    public ResultVO saveCategory(@RequestParam("type") String type) {
        Category category = new Category(type);
        try {
            int result = categoryMapper.insert(category);
            if (result != 0) {
                return R.success("添加成功");
            } else {
                return R.error(1, "添加失败");
            }
        } catch (DuplicateKeyException e) {
            return R.error(2, "该类型已存在，添加失败");
        }
    }

    @RequestMapping("/category/delete")
    public ResultVO deleteCategory(@RequestParam("type") String type) {
        int result = categoryMapper.delete(new QueryWrapper<Category>().eq("type", type));
        if (result != 0) {
            return R.success("删除成功");
        } else {
            return R.error(1, "删除失败");
        }
    }

    @RequestMapping("/category/update")
    public ResultVO updateCategory(@RequestParam("type") String type,
                                   @RequestParam("name") String name) {
        Category category = new Category();
        category.setType(Integer.valueOf(type));
        category.setName(name);
        int result = categoryMapper.updateById(category);
        if (result != 0) {
            return R.success("修改成功");
        } else {
            return R.error(1, "修改失败");
        }
    }

    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();//随机生成文件名
        String path = "E:/upload/images/";//上传文件的保存的目录，和项目分离，防止项目过大
        File dest = new File(path + fileName);
        if (!dest.getParentFile().exists()) {//E:/upload/images目录不存在则创建
            dest.getParentFile().mkdirs();//创建此目录，如果不存在父目录则创建父目录。
        }
        try {
            file.transferTo(dest);
            return "/images/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @RequestMapping("/products")
    public IPage products(@RequestParam(value = "page", defaultValue = "1") String page,
                          @RequestParam(value = "size", defaultValue = "10") String size,
                          @RequestParam(value = "searchName", defaultValue = "") String searchName) {
        Page<Product> productPage = new Page<>(Integer.valueOf(page), Integer.valueOf(size));
        IPage<Product> productIPage = productMapper.selectPage(productPage, new QueryWrapper<Product>().
                like("name", searchName).
                orderByAsc("id"));
        return productIPage;
    }

    @RequestMapping("/product/save")
    public ResultVO saveProduct(@RequestBody Product product) {
        try {
            int result = productMapper.insert(product);
            if (result != 0) {
                return R.success("添加成功");
            } else {
                return R.error(1, "添加失败");
            }
        } catch (DuplicateKeyException e) {
            return R.error(2, "该产品已存在，添加失败");
        }
    }

    @RequestMapping("/product/update")
    public ResultVO updateProduct(@RequestBody Product product) {
        int result = productMapper.updateById(product);
        if (result != 0) {
            return R.success("修改成功");
        } else {
            return R.error(1, "修改失败");
        }
    }

    @RequestMapping("/product/delete")
    public ResultVO deleteProduct(@RequestParam("id") String id) {
        int result = productMapper.delete(new QueryWrapper<Product>().eq("id", id));
        if (result != 0) {
            return R.success("删除成功");
        } else {
            return R.error(1, "删除失败");
        }
    }

    @RequestMapping("/orderList")
    public IPage orderList(@RequestParam(value = "page", defaultValue = "1") String page,
                           @RequestParam(value = "size", defaultValue = "10") String size,
                           @RequestParam(value = "orderId", defaultValue = "") String orderId) {
        Page<OrderMaster> orderMasterPage = new Page<>(Integer.parseInt(page), Integer.parseInt(size));
        IPage<OrderMaster> orderMasterIPage = orderMasterMapper.selectPage(orderMasterPage, new QueryWrapper<OrderMaster>().
                like("order_id", orderId).
                orderByDesc("create_time"));
        return orderMasterIPage;
    }

    @GetMapping("/order/handle")
    public ResultVO orderhandle(@RequestParam("orderId") String orderId) {
        OrderMaster orderMaster = orderMasterMapper.selectOne(new QueryWrapper<OrderMaster>().eq("order_id", orderId));
        orderMaster.setOrderStatus(1);
        int result = orderMasterMapper.updateById(orderMaster);
        if (result == 1) {
            return R.success("处理成功");
        } else {
            return R.error(1, "处理失败");
        }
    }

    @GetMapping("/order/detail")
    public List orderDetail(@RequestParam("orderId") String orderId) {
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
        return orderDetailList;
    }

    @GetMapping("/getWebSocketAddress")
    public String getWebSocketAddress() {
        String websocketAddress = String.format("ws://%s/websocket", projectUrlConfig.getSell());
        return websocketAddress;
    }

    @GetMapping("/table/list")
    public Map tableList() {
        Map<String, Object> map = new HashMap<>();
        map.put("tables", tableMapper.selectList(new QueryWrapper<Table>().orderByAsc("id")));
        map.put("serverUrl", "http://" + projectUrlConfig.getSell() + "/login?address=");
        return map;
    }

    @GetMapping("/table/create")
    public ResultVO createTable(Table table) {
        try {
            int result = tableMapper.insert(table);
            if (result == 1) {
                return R.success("创建成功！");
            } else {
                return R.error(1, "创建失败");
            }
        } catch (DuplicateKeyException e) {
            return R.error(1, "桌子已存在，创建失败");
        }
    }

    @GetMapping("/table/delete")
    public ResultVO deleteTable(@RequestParam("id") String id) {
        int result = tableMapper.delete(new QueryWrapper<Table>().eq("id", id));
        if (result == 1) {
            return R.success("删除成功");
        } else {
            return R.error(1, "删除失败");
        }
    }

    @GetMapping("/store/info")
    public Seller storeInfo(@RequestParam("id") String id) {
        return sellerMapper.selectOne(new QueryWrapper<Seller>().eq("id", id));
    }

    @GetMapping("/store/updata")
    public ResultVO storeUpdate(Seller seller) {
        int result=sellerMapper.updateById(seller);
        if(result==1){
            return R.success("更新成功！");
        }else{
            return R.error(1,"更新失败！");
        }
    }

    @PostMapping("/serve/login")
    public ResultVO serveLosin(@RequestBody Map<String, String> map) {
        User user = userMapper.selectOne(new QueryWrapper<User>().
                eq("username", map.get("username")).
                eq("password", map.get("password")));
        if (user != null) {
            return R.success("登录成功！");
        } else {
            return R.error(1, "登录失败，账号或密码错误");
        }
    }
}
